package com.whisperarts.financer.app.actions;

import org.eclipse.jface.action.Action;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.window.Window;
import org.eclipse.ui.ISelectionListener;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.actions.ActionFactory.IWorkbenchAction;
import org.eclipse.ui.plugin.AbstractUIPlugin;

import com.whisperarts.financer.app.Application;
import com.whisperarts.financer.app.dialogs.AddCategoryDialog;
import com.whisperarts.financer.app.utils.StatusLineUtils;
import com.whisperarts.financer.app.utils.UIUtils;
import com.whisperarts.financer.dao.AccountsDAO;
import com.whisperarts.financer.model.transaction.Category;

public class AddCategoryAction extends Action implements 
	ISelectionListener, IWorkbenchAction {
	
	private final IWorkbenchWindow window;
	public final static String ID = "com.whisperarts.financer.app.actions.addCategory";
	private IStructuredSelection selection;
	
	
	public AddCategoryAction(IWorkbenchWindow window) {
		this.window = window;
		setId(ID);
		setText("&Add Category");
		setToolTipText("Create new category");
		setImageDescriptor(AbstractUIPlugin.imageDescriptorFromPlugin(Application.PLUGIN_ID, ISharedImages.IMG_OBJ_FOLDER));
		window.getSelectionService().addSelectionListener(this);
	}
	
	@Override
	public void selectionChanged(IWorkbenchPart part, ISelection incoming) {
//		if (incoming instanceof IStructuredSelection) {
//			selection = (IStructuredSelection) incoming;
//			setEnabled(selection.size() == 1 &&
//					selection.getFirstElement() instanceof AccountsCategory);
//		} else {
			setEnabled(true);
//		}
	}
	
	@Override
	public void dispose() {
		window.getSelectionService().removeSelectionListener(this);
	}
	
	@Override
	public void run() {
		AddCategoryDialog dialog = new AddCategoryDialog(window.getShell());
		if (dialog.open() == Window.OK) {
			Category category = dialog.getCategory();
			if (AccountsDAO.saveCategory(category) == 0) {
				AccountsDAO.getCategories().put(category.getId(), category);
				AccountsDAO.getCategories().get(category.getParentId()).addSub(category);
				UIUtils.refreshCategoryNode(AccountsDAO.getCategories().get(category.getParentId()));
				StatusLineUtils.setMessage("Category '" + category.getName() + "' created");				
			}
		}
		
		
//		try {
//			PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().showView(CategoryView.ID);
//		} catch (PartInitException e) {
//			e.printStackTrace();
//		}
		
//			IWorkbenchPage page = 
//			Workbench.getInstance().getActiveWorkbenchWindow().getActivePage();
//
//
//			//get the reference for your viewId
//			IViewReference ref = page.findViewReference(CategoryView.ID);
//
//			//release the view
//			page.hideView(ref);
	}

}
